package com.backstage.kits;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.codec.binary.Base64;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yanhao on 2017/7/16.
 */
public class JwtKits {

    public static String createToken(String key, Object o) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        // header
        JWTCreator.Builder builder = JWT.create().withHeader(map);
        // payload
        Field[] fields = o.getClass().getDeclaredFields();

        for (Field field: fields) {
            field.setAccessible(true);
            builder = builder.withClaim(field.getName(), String.valueOf(field.get(o)));
        }

        // 加密
        return builder.sign(Algorithm.HMAC256(key));
    }

    public static JSONObject payLoad(String token){
        DecodedJWT jwt = JWT.decode(token);
        try {
            return (JSONObject)JSONObject.parse(new String(Base64.decodeBase64(jwt.getPayload()), "UTF-8"));
        } catch (Exception e) {
            return null;
        }
    }


    public static boolean verifyToken(String token, String key) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key))
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        return (claims!=null && claims.size() > 0);
    }
}
